package org.ielts.action.security;

import java.io.IOException;
import java.sql.SQLException;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

import org.ielts.action.BaseAction;
import org.ielts.domain.security.Role;
import org.ielts.service.security.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.xml.sax.SAXException;

import com.opensymphony.xwork2.ActionContext;
import com.yifeng.dto.FormRow;
import com.yifeng.dto.IDtoRow;
import com.yifeng.modules.annotations.Module;
import com.yifeng.modules.annotations.Operation;
import com.yifeng.security.authorization.Authorization;
import com.yifeng.security.privilege.Catalog;
import com.yifeng.security.privilege.Privilege;
import com.yifeng.security.privilege.Privileges;
import com.yifeng.utils.JsonResultBuilder;
import static com.yifeng.struts2.RequestParameters.*;
import static com.yifeng.struts2.ResultParameters.*;
import static com.yifeng.struts2.ResultConstants.*;
import static com.yifeng.struts2.ActionUtils.*;

@Module(namespaceName = "security")
public class PrivilegeAction extends BaseAction {

	@Autowired
	RoleService roleService;

	@Operation(result = FILL)
	public String setPrivilege() {
		String roleId = getForm().readString("id");

		Role role = roleService.findRole(roleId);

		put("role", role);

		return FILL;
	}

	@Autowired
	Authorization authorization;

	// 查询
	@Operation(operationText = "查询页面初始化", result = FILL)
	public String listPrivilege() throws IOException, SAXException, SQLException {
		String roleId = getForm().readString("roleId");

		Iterable<Privilege> privileges = authorization.findPrivilegesByPrincipal(roleId);

		Set<String> privilegeStrs = new HashSet<String>();

		for (Privilege privilege : privileges) {
			if (privilege != null) {
				privilegeStrs.add(privilege.getId());
			}
		}

		Catalog catalog = Privileges.getInstance().getCatalog();

		put("catalog", catalog);
		put("privileges", privilegeStrs);
		setRootMap(ActionContext.getContext());
		return FREEMARKER;
	}

	@Operation(operationText = "设置角色权限", result = JSON)
	public String doSetPrivilege() {
		FormRow form = getForm();
		String roleId = form.readString("roleId");
		String[] privileges = form.readStrings("privilege");

		authorization.authorize(roleId, privileges);

		setJson(JsonResultBuilder.success(true).msg("设置权限成功。").json());

		return JSON;
	}
}
